<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查询结果表格模板</title>
    <!-- Bootstrap CSS -->
    <link href="https://unpkg.com/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid mt-3">
        <!-- 查询区域 -->
        <div class="card mb-3">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-search me-2"></i>查询条件
                </h5>
            </div>
            <div class="card-body">
                <!-- 动态查询组件容器 -->
                <div id="fixedQueryArea"></div>
            </div>
        </div>
        
        <!-- 结果区域 -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="fas fa-table me-2"></i>查询结果
                    <span id="resultCount" class="badge bg-secondary ms-2">0</span>
                </h5>
                <div class="btn-group">
                    <button class="btn btn-success btn-sm" id="exportBtn" disabled>
                        <i class="fas fa-download me-1"></i>导出Excel
                    </button>
                </div>
            </div>
            <div class="card-body">
                <!-- 表格容器 -->
                <div id="queryResults" class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead id="queryTableHead" class="table-dark"></thead>
                        <tbody id="queryTableBody"></tbody>
                    </table>
                    <!-- 分页容器 -->
                    <nav aria-label="查询结果分页">
                        <ul class="pagination justify-content-center" id="queryPagination"></ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://unpkg.com/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- 通用组件 -->
    <script src="/static/js/FixedQueryArea.js"></script>
    <script src="/static/js/QueryResultTable.js"></script>
    
    <script>
        // ==================== 模板使用示例 ====================
        
        // 配置变量（各模块需要自定义）
        const MODULE_CONFIG = {
            tableName: 'students',  // 表名：students, vision_records, intervention_records, phone_followup
            queryApi: '/api/students/query',  // 查询API
            exportApi: '/api/students/export',  // 导出API
            pageSize: 20  // 每页显示数量
        };
        
        // 全局变量
        let queryFieldsConfig = [];
        let tableFieldsConfig = [];
        let currentPage = 1;
        let totalRecords = 0;
        let currentParams = {};
        
        // ==================== 初始化 ====================
        
        document.addEventListener('DOMContentLoaded', function() {
            initializeComponents();
        });
        
        async function initializeComponents() {
            try {
                // 1. 加载查询字段配置
                await loadQueryFieldsConfig();
                
                // 2. 加载表格字段配置
                await loadTableFieldsConfig();
                
                // 3. 渲染查询组件
                renderQueryComponent();
                
                // 4. 绑定导出事件
                bindExportEvents();
                
                console.log('✅ 组件初始化完成');
                
            } catch (error) {
                console.error('❌ 组件初始化失败:', error);
                showAlert('组件初始化失败，请刷新页面重试', 'danger');
            }
        }
        
        // ==================== 配置加载 ====================
        
        async function loadQueryFieldsConfig() {
            const response = await fetch('/api/config/query-fields');
            const result = await response.json();
            if (result.success) {
                queryFieldsConfig = result.fields;
            } else {
                throw new Error(result.error || '加载查询字段配置失败');
            }
        }
        
        async function loadTableFieldsConfig() {
            const response = await fetch(`/api/config/table-fields/${MODULE_CONFIG.tableName}`);
            const result = await response.json();
            if (result.success) {
                tableFieldsConfig = result.fields;
            } else {
                throw new Error(result.error || '加载表格字段配置失败');
            }
        }
        
        // ==================== 组件渲染 ====================
        
        function renderQueryComponent() {
            // 自定义按钮配置（可选）
            const customButtons = [
                {
                    text: '高级查询',
                    className: 'btn btn-info btn-sm',
                    onclick: function() {
                        showAdvancedQuery();
                    }
                }
            ];
            
            // 渲染查询组件
            renderFixedQueryArea(
                queryFieldsConfig,
                'fixedQueryArea',
                handleSearch,
                handleClear,
                true,  // showColumnConfig
                customButtons
            );
        }
        
        // ==================== 事件处理 ====================
        
        function handleSearch(params) {
            currentParams = params;
            currentPage = 1;
            performQuery();
        }
        
        function handleClear() {
            currentParams = {};
            currentPage = 1;
            clearResults();
        }
        
        function handlePageChange(page) {
            currentPage = page;
            performQuery();
        }
        
        // ==================== 查询逻辑 ====================
        
        async function performQuery() {
            try {
                showLoading(true);
                
                const queryParams = {
                    ...currentParams,
                    page: currentPage,
                    per_page: MODULE_CONFIG.pageSize
                };
                
                const response = await fetch(MODULE_CONFIG.queryApi, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(queryParams)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    renderQueryResults(result.data, result.pagination);
                    updateResultCount(result.pagination.total);
                    enableExport(true);
                } else {
                    throw new Error(result.error || '查询失败');
                }
                
            } catch (error) {
                console.error('❌ 查询失败:', error);
                showAlert('查询失败，请检查网络连接后重试', 'danger');
                clearResults();
            } finally {
                showLoading(false);
            }
        }
        
        function renderQueryResults(data, pagination) {
            // 操作按钮配置
            const actionButtons = [
                {
                    text: '查看',
                    className: 'btn btn-primary btn-sm',
                    onclick: function(row) {
                        viewRecord(row);
                    }
                },
                {
                    text: '编辑',
                    className: 'btn btn-warning btn-sm',
                    onclick: function(row) {
                        editRecord(row);
                    }
                }
            ];
            
            // 分页配置
            const paginationConfig = {
                total: pagination.total,
                page: pagination.page,
                perPage: pagination.per_page,
                onPageChange: handlePageChange
            };
            
            // 渲染表格
            renderQueryResultTable(data, tableFieldsConfig, 'query', {
                pagination: paginationConfig,
                actionButtons: actionButtons,
                showRowNumber: true,
                onRowClick: function(row) {
                    console.log('行点击:', row);
                }
            });
        }
        
        // ==================== 辅助函数 ====================
        
        function clearResults() {
            document.getElementById('queryTableBody').innerHTML = '';
            document.getElementById('queryPagination').innerHTML = '';
            updateResultCount(0);
            enableExport(false);
        }
        
        function updateResultCount(count) {
            document.getElementById('resultCount').textContent = count;
            totalRecords = count;
        }
        
        function enableExport(enabled) {
            const exportBtn = document.getElementById('exportBtn');
            exportBtn.disabled = !enabled;
        }
        
        function showLoading(show) {
            // 这里可以添加加载动画
            if (show) {
                document.getElementById('queryTableBody').innerHTML = 
                    '<tr><td colspan="20" class="text-center py-4"><i class="fas fa-spinner fa-spin"></i> 正在查询...</td></tr>';
            }
        }
        
        function showAlert(message, type = 'info') {
            // 简单的警告框显示
            alert(message);
        }
        
        // ==================== 业务操作 ====================
        
        function viewRecord(row) {
            // 查看记录详情（需要各模块自定义）
            console.log('查看记录:', row);
        }
        
        function editRecord(row) {
            // 编辑记录（需要各模块自定义）
            console.log('编辑记录:', row);
        }
        
        function showAdvancedQuery() {
            // 高级查询功能（需要各模块自定义）
            console.log('显示高级查询');
        }
        
        // ==================== 导出功能 ====================
        
        function bindExportEvents() {
            document.getElementById('exportBtn').addEventListener('click', function() {
                if (totalRecords === 0) {
                    showAlert('没有数据可以导出', 'warning');
                    return;
                }
                exportToExcel();
            });
        }
        
        async function exportToExcel() {
            try {
                const response = await fetch(MODULE_CONFIG.exportApi, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(currentParams)
                });
                
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${MODULE_CONFIG.tableName}_${new Date().toISOString().slice(0, 10)}.xlsx`;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                } else {
                    throw new Error('导出失败');
                }
                
            } catch (error) {
                console.error('❌ 导出失败:', error);
                showAlert('导出失败，请重试', 'danger');
            }
        }
    </script>
</body>
</html>
